import java.io.Serializable;


@SuppressWarnings("serial")
public class Match implements MatchNode, Serializable {

	static String CONST_LF = "\n";
	static String DRAW_LINE = "} ";
	static String DRAW_INDENT = "                    ";
	
	private int id;
	private int depth = 1;
	private MatchNode leftNode;
	private MatchNode rightNode;
	private int leftScore;
	private int rightScore;
	
	
	Match(int id, MatchNode m1, MatchNode m2) {
		this.id = id;
		leftNode = m1;
		rightNode = m2;
		leftScore = -1;
		rightScore = -1;
	}
	
	public int getDepth() {
		return (leftNode.getDepth() > rightNode.getDepth()) ? leftNode.getDepth() + 1 : rightNode.getDepth() + 1;
	}
	
	public String getIndent() {
		String result = "";
		for(int i=0;i<depth-1;i++) {
			result += DRAW_INDENT;
		}
		return result;
	}
	
	public void setDepth(int d) {
		depth = d;
	}

	public void calcDepth(int d) {
		depth = d;
		
		leftNode.calcDepth(d-1);
		rightNode.calcDepth(d-1);
	}
	
	public int getId() {
		return id;
	}
	
	
	public String toString() {
		return toString(DrawLevel.DRAW_NAME);
	}
	
	public String toString(DrawLevel lv) {
		String result;
		String leftText = leftNode.toString(lv);
		String centerText = "";
		if( getWinnerNode() == null ){
			centerText = getIndent() + DRAW_LINE + "?";
		}
		else {
			centerText = getIndent() + DRAW_LINE + getWinnerNode().getInfo(lv) + getScore();
		}
		
		String rightText = rightNode.toString(lv);
		
		result = String.format("%s%s%s%s%s", leftText, CONST_LF, centerText, CONST_LF, rightText);
		
		return result; 
	}
	
	public String getInfo(DrawLevel lv) {
		String result = "";
		String match1, match2;
		if( leftNode instanceof Match ) {
			match1 = String.format("%32s","Winner of Match #" + (leftNode.getId() + 1));
		} 
		else {
			match1 = String.format("%32s",leftNode.getInfo(lv));
		}
		
		if( rightNode instanceof Match ) {
			match2 = String.format("%-32s","Winner of Match #" + (rightNode.getId() + 1));
		} 
		else {
			match2 = String.format("%-32s",rightNode.getInfo(lv));
		}
		
		result = String.format("Match #%2d, %s vs %s",id + 1, match1, match2);
		
		return result;
	}

	public void setScore(int s1, int s2) {
		leftScore = s1;
		rightScore = s2;
	}
	
	public String getScore() {
		return String.format(" (%d:%d)", leftScore, rightScore);
	}
	
	public MatchNode getWinnerNode() {
		if(leftScore == -1 || rightScore == -1) {
			return null;
		}
		else if(leftScore > rightScore) {
			return leftNode.getWinnerNode();
		}
		else { 
			return rightNode.getWinnerNode();
		}
	}
}
